package cn.code.service;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class FileProcessingService {

    private final Tika tika = new Tika();

    /**
     * 提取文件内容
     */
    public String extractContent(MultipartFile file) throws IOException, TikaException {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();

        if (fileName == null) {
            return tika.parseToString(file.getInputStream());
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 根据文件类型使用不同的解析方式
            if (fileName.toLowerCase().endsWith(".docx")) {
                return extractDocxContent(inputStream);
            } else if (fileName.toLowerCase().endsWith(".xlsx") || fileName.toLowerCase().endsWith(".xls")) {
                return extractExcelContent(inputStream);
            } else if (fileName.toLowerCase().endsWith(".pdf")) {
                return extractPdfContent(inputStream);
            } else {
                // 使用Tika处理其他文件类型
                return tika.parseToString(inputStream);
            }
        }
    }

    /**
     * 提取Word文档内容
     */
    private String extractDocxContent(InputStream inputStream) throws IOException {
        try (XWPFDocument document = new XWPFDocument(inputStream);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            return extractor.getText();
        }
    }

    /**
     * 提取Excel文档内容
     */
    private String extractExcelContent(InputStream inputStream) throws IOException {
        StringBuilder content = new StringBuilder();
        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                content.append("Sheet: ").append(sheet.getSheetName()).append("\n");
                
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        switch (cell.getCellType()) {
                            case STRING:
                                content.append(cell.getStringCellValue()).append("\t");
                                break;
                            case NUMERIC:
                                content.append(cell.getNumericCellValue()).append("\t");
                                break;
                            case BOOLEAN:
                                content.append(cell.getBooleanCellValue()).append("\t");
                                break;
                            case FORMULA:
                                content.append(cell.getCellFormula()).append("\t");
                                break;
                            default:
                                content.append("\t");
                        }
                    }
                    content.append("\n");
                }
                content.append("\n");
            }
        }
        return content.toString();
    }

    /**
     * 提取PDF文档内容
     */
    private String extractPdfContent(InputStream inputStream) throws IOException, TikaException {
        // Tika可以很好地处理PDF
        return tika.parseToString(inputStream);
    }

    /**
     * 检查文件类型是否支持
     */
    public boolean isSupportedFileType(String fileName) {
        if (fileName == null) return false;
        
        String lowerFileName = fileName.toLowerCase();
        return lowerFileName.endsWith(".pdf") ||
               lowerFileName.endsWith(".docx") ||
               lowerFileName.endsWith(".doc") ||
               lowerFileName.endsWith(".xlsx") ||
               lowerFileName.endsWith(".xls") ||
               lowerFileName.endsWith(".jpg") ||
               lowerFileName.endsWith(".jpeg") ||
               lowerFileName.endsWith(".png") ||
               lowerFileName.endsWith(".mp4") ||
               lowerFileName.endsWith(".mp3") ||
               lowerFileName.endsWith(".wav") ||
               lowerFileName.endsWith(".txt");
    }

    /**
     * 获取文件类型
     */
    public String getFileType(String fileName) {
        if (fileName == null) return "unknown";
        
        if (fileName.toLowerCase().endsWith(".pdf")) return "PDF";
        if (fileName.toLowerCase().endsWith(".docx") || fileName.toLowerCase().endsWith(".doc")) return "Word";
        if (fileName.toLowerCase().endsWith(".xlsx") || fileName.toLowerCase().endsWith(".xls")) return "Excel";
        if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg")) return "Image";
        if (fileName.toLowerCase().endsWith(".png")) return "Image";
        if (fileName.toLowerCase().endsWith(".mp4")) return "Video";
        if (fileName.toLowerCase().endsWith(".mp3") || fileName.toLowerCase().endsWith(".wav")) return "Audio";
        if (fileName.toLowerCase().endsWith(".txt")) return "Text";
        
        return "Other";
    }
}
